import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
/* 获取用户信息的API */
import { getUserInfoAPI } from '../api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '', // 用户的token
    userInfo: {}// 定义用户信息对象
  },
  getters: {
    nickname: state => state.userInfo.nickname,
    username: state => state.userInfo.username,
    user_pic: state => state.userInfo.user_pic
  },
  mutations: {
    /* 更新token的mutation函数 */
    updateToken (state, newToken) {
      state.token = newToken
    },
    updateUserInfo (state, info) {
      state.userInfo = info
    }
  },
  actions: {
    /* 定义初始化用户的基本信息的action函数 */
    async initUserInfo ({ commit }) {
      const { data: res } = await getUserInfoAPI()
      if (res.code === 0) {
        commit('updateUserInfo', res.data)
      }
    }
  },
  modules: {
  },
  plugins: [createPersistedState()]
})
